package com.glorious.gcontacts.spring.repositories;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.glorious.gcontacts.model.GoogleContactInfo;
import com.glorious.gcontacts.model.UserData;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

@Repository
public class UserDataDTO
{
	private PersistenceRepository persistenceRepository;

	@Autowired
	public void setPersistenceRepository(PersistenceRepository persistenceRepository)
	{
		this.persistenceRepository = persistenceRepository;
	}
	
	public UserData getUserData(User user)
	{
		return getUserData(user.getUserId());
	}
	
	public UserData getUserData(String userId)
	{
		PersistenceManager manager = persistenceRepository.getManager();
		UserData data = null;
		try
		{
			data = manager.getObjectById(UserData.class, userId);
			data.getGoogleContactInfo();
			data = manager.detachCopy(data);
		}
		catch(JDOObjectNotFoundException e)
		{
			
		}
		finally
		{
			manager.close();
		}
		return data;
	}
	
	public void saveUserData(UserData data)
	{
		PersistenceManager manager = persistenceRepository.getManager();
		try
		{
			data.setKey(data.getUser().getUserId());
			if(data.getGoogleContactInfo() != null)
			{
				data.getGoogleContactInfo().setKey(KeyFactory.createKey(GoogleContactInfo.class.getSimpleName(), data.getUser().getUserId()));
			}
			manager.makePersistent(data);
		}
		finally
		{
			manager.close();
		}
	}
}
